package com.songlanyun.modules.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import com.songlanyun.modules.shop.dao.UnionBusinessClassifyDao;
import com.songlanyun.modules.shop.entity.ShopEntity;
import com.songlanyun.modules.shop.entity.UnionBusinessClassifyEntity;
import com.songlanyun.modules.shop.entity.UnionBusinessRelationEntity;
import com.songlanyun.modules.shop.model.dto.UnionBusinessClassifyDTO;
import com.songlanyun.modules.shop.model.dto.UnionBusinessRelationDTO;
import com.songlanyun.modules.shop.service.ShopService;
import com.songlanyun.modules.shop.service.UnionBusinessClassifyService;
import com.songlanyun.modules.shop.service.UnionBusinessRelationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("yxtUnionBusinessClassifyService")
public class UnionBusinessClassifyServiceImpl extends ServiceImpl<UnionBusinessClassifyDao, UnionBusinessClassifyEntity> implements UnionBusinessClassifyService {

    @Autowired
    private ShopService shopService;

    @Autowired
    private UnionBusinessRelationService unionBusinessRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String name = MapUtil.getStr(params, "name");
        String startTime = MapUtil.getStr(params, "start_time");
        String endTime = MapUtil.getStr(params, "end_time");

        IPage<UnionBusinessClassifyEntity> page = this.page(
                new Query<UnionBusinessClassifyEntity>().getPage(params),
                new LambdaQueryWrapper<UnionBusinessClassifyEntity>()
                        .like(StringUtils.isNotBlank(name), UnionBusinessClassifyEntity::getName, name)
                        .ge(StringUtils.isNotBlank(startTime), UnionBusinessClassifyEntity::getCreateTime, startTime)
                        .le(StringUtils.isNotBlank(endTime), UnionBusinessClassifyEntity::getCreateTime, endTime)
                        .orderByAsc(UnionBusinessClassifyEntity::getRank)
                        .orderByDesc(UnionBusinessClassifyEntity::getCreateTime)
        );
        return new PageUtils(page);
    }

    @Override
    public UnionBusinessClassifyEntity getById(Long id, boolean tw) {
        UnionBusinessClassifyEntity classifyEntity = this.baseMapper.selectById(id);
        if (ObjectUtil.isNull(classifyEntity) && tw) {
            throw new RRException("联盟商家分类不存在");
        }
        return classifyEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Long userId, UnionBusinessClassifyDTO dto) {
        UnionBusinessClassifyEntity classifyEntity = BeanUtil.toBean(dto, UnionBusinessClassifyEntity.class);
        classifyEntity.setCreateId(userId);
        classifyEntity.setUpdateId(userId);
        this.baseMapper.insert(classifyEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(Long userId, UnionBusinessClassifyDTO dto) {
        UnionBusinessClassifyEntity classifyEntity = this.getById(dto.getId(), true);
        BeanUtil.copyProperties(dto, classifyEntity);
        classifyEntity.setUpdateId(userId);
        this.baseMapper.updateById(classifyEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        //询是否有商家关联该便民服务分类
        Integer count = unionBusinessRelationService.lambdaQuery().eq(UnionBusinessRelationEntity::getClassifyId, id).count();
        if (count > 0) {
            throw new RRException("该联盟商家分类下存在商家，不能删除");
        }
        this.baseMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setClassify(UnionBusinessRelationDTO dto) {

        ShopEntity shop = shopService.getById(dto.getShopId(), true);
        //先删除之前的关系
        unionBusinessRelationService.remove(
                new LambdaQueryWrapper<UnionBusinessRelationEntity>()
                        .eq(UnionBusinessRelationEntity::getShopId, shop.getId())
        );
        //保存关系
        if (ArrayUtil.isNotEmpty(dto.getClassifyIds())) {
            List<UnionBusinessRelationEntity> list = new ArrayList<>();
            for (Long classifyId : dto.getClassifyIds()) {
                list.add(new UnionBusinessRelationEntity(shop.getId(), classifyId));
            }
            unionBusinessRelationService.saveBatch(list);
        }

    }

    @Override
    public List<UnionBusinessClassifyEntity> queryListByShopId(Long shopId) {
        List<UnionBusinessRelationEntity> list = unionBusinessRelationService.lambdaQuery().eq(UnionBusinessRelationEntity::getShopId, shopId).list();
        if (CollectionUtil.isNotEmpty(list)) {
            List<Long> classifyIds = list.stream().map(UnionBusinessRelationEntity::getClassifyId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(classifyIds)) {
                return this.lambdaQuery().in(UnionBusinessClassifyEntity::getId, classifyIds).list();
            }
        }

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void show(Long id) {
        UnionBusinessClassifyEntity classify = this.getById(id, true);
        classify.setIsShow(!classify.getIsShow());
        this.updateById(classify);
    }

}
